package com.hns.phone.base.web;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;

import com.hns.can.base.entity.SysOperateLogEntity;
import com.hns.can.base.entity.SysRoleEntity;
import com.hns.can.base.entity.SysUserEntity;
import com.hns.can.base.service.LoginService;
import com.hns.can.base.service.SysAuthorityButtonService;
import com.hns.can.base.service.SysAuthorityFuncService;
import com.hns.can.base.service.SysFuncService;
import com.hns.can.base.service.SysRoleService;
import com.hns.can.base.service.SysUserService;
import com.hns.can.common.domain.ReturnResult;
import com.hns.can.common.web.BaseController;
import com.hns.frame.enumrate.EnabledSt;
import com.hns.frame.enumrate.LoginType;
import com.hns.frame.enumrate.RequestResult;
import com.hns.frame.exception.ParameterFormatException;
import com.hns.frame.exception.ParameterIsNullException;
import com.hns.frame.util.ResponseUtil;
import com.hns.tool.pub.AppUtil;
import com.hns.tool.pub.PubUtil;
import com.hns.tool.pub.UtilString;

/**
 * 登录功能
 * @author:zhangyu
 * @email:zhangyu2222z@sina.cn
 * @version Revision 2.0.0
 */
@Controller
//@SessionAttributes({"SES_CURRENTUSER","SES_ORGANLIST", "SES_ROLELIST", "SES_AUTHORITY", "SES_THIRDMENU", "SES_ALLAUTHORITY"})
@RequestMapping("/api/phoneLogon")
public class PhoneLogonController extends BaseController {
    
    @Autowired
    private SysRoleService sysRoleService;
    
    @Autowired
    private SysFuncService sysFuncService;
    
//    @Autowired
//    private BaseOrganService baseOrganService;
    
    @Autowired
    private LoginService loginService;
    
    @Autowired
    private SysAuthorityButtonService sysAuthorityButtonService;
    
    //TODO
//    @Autowired
//    private SysOperateLogService sysOperateLogService;
    
    @Autowired
    private TaskExecutor        taskExecutor;
    
    @Autowired
    SysUserService sysUserService;
    
//    @Autowired
//    private IndexService   indexService;
    
//    @Autowired
//    private SafeBehaviourService   safeBehaviourService;
    
//    @Autowired
//    private BaseLineInfoService baseLineInfoService;
    
    @Autowired
    private SysAuthorityFuncService sysAuthorityFuncService;
    
    private ReturnResult reslutVo = new ReturnResult();
    
    
   /* *//**
     * 登录入口
     * @param request
     * @param response
     * @param map
     * @return
     * @throws Exception
     * @author:Fisher
     * @email:zhuangcaijin@126.com
     *//*
    @RequestMapping("/enter")
    @ResponseBody
    public Object enter(HttpServletRequest request, Map<String, Object> map) throws Exception {
    	ReturnResult vo = null;
        AppUserDetailsImpl currentLogin = this.getAppCurrentUser();
        if (currentLogin == null) {
            vo = new ReturnResult(RequestResult.FAIL.getDescr(), RequestResult.FAIL.getFlag(), false);
            return vo;
        }else{
            if("1".equals(currentLogin.getUser().getAllowMobileLogin())){// 允许手机登录
                vo = new ReturnResult(RequestResult.SUCCESS.getDescr(), RequestResult.SUCCESS.getFlag());
            }else{
                vo = new ReturnResult(RequestResult.FORBIDDEN.getDescr(), RequestResult.FORBIDDEN.getFlag(), false);
            }
        }
        BigDecimal beginTime = new BigDecimal(System.currentTimeMillis()); // 记录登录开始时间
        // 获取当前用户信息
        final SysUserEntity currentUser = currentLogin.getUser();
        // 获取用户对应的角色
        List<SysRoleEntity> sysRoleList = sysRoleService.getSysRoleListByUserId(currentUser.getId());
        // 将用户对应的角色列表放入session
        map.put("SES_CURRENTUSER", currentUser);
        // 将用户对应的角色列表放入session
        map.put("SES_ROLELIST", sysRoleList);
        // 获取角色对应的组织机构权限
        List<String> sysAuthorityResourceEntityList = loginService.getAuthorityResource(sysRoleList);
        map.put("SES_ORGANLIST", sysAuthorityResourceEntityList);
        // 获取用户对应的资源字段值
        List<SysAuthrityFieldValueEntity> authFieldValueList = sysAuthorityFuncService.getAuthFieldValue(currentUser.getId());
        SysCache.setAuthrityFieldValue(currentUser.getId(), authFieldValueList);
        SysUserEntity user = currentLogin.getUser();
        vo.setObj(sysUserService.findSysUserByName(user));
        BigDecimal endTime = new BigDecimal(System.currentTimeMillis()); // 记录登录结束时间
        
        //写入日志
		String ip = PubUtil.getRemortIP((HttpServletRequest) request);
		SysOperateLogEntity entity = new SysOperateLogEntity();
		entity.setLogId(UtilString.getUUID());
		entity.setCorpId(currentUser.getCorpId());
		entity.setOprId(currentUser.getId());
		entity.setMnpltTime(new Date());
		entity.setMnpltUrl("/phoneLogon/enter.htm");
		entity.setMnpltDura(endTime.subtract(beginTime));
		entity.setIpAdr(ip);
		// ClientMacAddr mac = new ClientMacAddr(ip);
		// entity.setMacAdr(mac.GetRemoteMacAddr());
		// entity.setMnpltFunc(menuVo.getId());
		// 区分登录的途径
		String loginType = currentUser.getLoginType();
		if (LoginType.ANDROID.getFlag().equals(loginType)) {
			entity.setMnpltType("OLOG0011");
		} else if (LoginType.IOS.getFlag().equals(loginType)) {
			entity.setMnpltType("OLOG0013");
		} else {
			entity.setMnpltType("OLOG0013");
		}
		entity.setSystemId("CLOUD_CAN_V2.0");
		loginService.saveSysOperateLog(entity);
        
        
        return vo;
    }*/
    
    @RequestMapping("/phLogin")
    @ResponseBody
    public Object phLogin(HttpServletRequest request, ModelMap map) {
        ReturnResult returnResult = null;
        BigDecimal beginTime = new BigDecimal(System.currentTimeMillis()); // 记录登录开始时间
        try {
            JSONObject JSONParams = this.getParameter_JSON();
            String j_username = AppUtil.isNotEmpty(JSONParams.get("j_username"), "用户名").toString();
            String j_password = AppUtil.isNotEmpty(JSONParams.get("j_password"), "密码").toString();
            final Md5PasswordEncoder md5 = new Md5PasswordEncoder();
            md5.setEncodeHashAsBase64(false);
            String currentPwd = md5.encodePassword(j_password, PubUtil.filterNULL(j_username));
            String loginType = JSONParams.optString("type");
       
            Map<String,Object> params = new HashMap<String,Object>();
            params.put("acctName", j_username);
            params.put("password", currentPwd);
            params.put("isClosed", EnabledSt.DISABLE.getFlag());
            
            SysUserEntity currentUser = sysUserService.getSysUserEntityByCheck(params);
            if(currentUser != null){
                request.getSession().setAttribute("PHONE_CURRENTUSER", currentUser);
                //获取用户对应角色
                List<SysRoleEntity> sysRoleList = sysRoleService.getSysRoleListByUserId(currentUser.getId());
                SysRoleEntity sysRoleEntity = sysRoleList.get(0);
                currentUser.setOfficename(sysRoleEntity.getName());
                request.getSession().setAttribute("CURRENTUSERROLELIST", sysRoleList);
                BigDecimal endTime = new BigDecimal(System.currentTimeMillis()); // 记录登录结束时间
                SysOperateLogEntity entity = new SysOperateLogEntity();
                entity.setLogId(UtilString.getUUID());
                entity.setCorpId(currentUser.getCorpId());
                entity.setOprId(currentUser.getId());
                entity.setMnpltTime(new Date());
                entity.setMnpltUrl("/api/phoneLogon/phLogin.htm");
                entity.setMnpltDura(endTime.subtract(beginTime));
                entity.setIpAdr(PubUtil.getRemortIP((HttpServletRequest) request));
                if (LoginType.ANDROID.getFlag().equals(loginType)) {
                    entity.setMnpltType("OLOG0011");
                } else if (LoginType.IOS.getFlag().equals(loginType)) {
                    entity.setMnpltType("OLOG0013");
                } else {
                    entity.setMnpltType("OLOG0013");
                }
                loginService.saveSysOperateLog(entity);
                
                returnResult = new ReturnResult(currentUser, RequestResult.SUCCESS.getFlag(), true);
            }else{
                returnResult = new ReturnResult(RequestResult.FAIL.getDescr(), RequestResult.FAIL.getFlag(), false);
            }
        } catch(ParameterFormatException e){
            returnResult = new ReturnResult(e.getMessage(), "0", false);
        } catch(ParameterIsNullException e){
            returnResult =  new ReturnResult(e.getMessage(), "0", false);
        } catch(Exception e){
            returnResult =  new ReturnResult(e.getMessage(), "0", false);
        } 
        return returnResult;
    }
	
	/**
	 * @param status
	 * @param request
	 * @return
	 * @author:Fisher
	 * @email:zhuangcaijin@126.com
	 * @创建日期:2014-2-28
	 * @功能说明：退出
	 */
	@RequestMapping("/commonQuit")
	public String commonQuit(SessionStatus status, HttpServletRequest request) throws Exception{
	    //SysUserEntity currentUser = (SysUserEntity) request.getSession().getAttribute("SES_CURRENTUSER");
	    if(PubUtil.isNotEmpty(this.getAppCurrentUser())){
	    	SysUserEntity currentUser = this.getAppCurrentUser().getUser();
	        BigDecimal beginTime = new BigDecimal(System.currentTimeMillis()); // 记录注销开始时间
	        
	        status.setComplete();
	        
	        BigDecimal endTime = new BigDecimal(System.currentTimeMillis()); // 记录注销结束时间
	        
	        // 添加注销日志
	        String ip = PubUtil.getRemortIP((HttpServletRequest) request);
			SysOperateLogEntity entity = new SysOperateLogEntity();
			entity.setLogId(UtilString.getUUID());
			entity.setCorpId(currentUser.getCorpId());
			entity.setOprId(currentUser.getId());
			entity.setMnpltTime(new Date());
			entity.setMnpltUrl("/phoneLogon/commonQuit.htm");
			entity.setMnpltDura(endTime.subtract(beginTime));
			entity.setIpAdr(ip);
			// ClientMacAddr mac = new ClientMacAddr(ip);
			// entity.setMacAdr(mac.GetRemoteMacAddr());
			// entity.setMnpltFunc(menuVo.getId());
			// 区分登录的途径
			String loginType = currentUser.getLoginType();
			if (LoginType.ANDROID.getFlag().equals(loginType)) {
				entity.setMnpltType("OLOG0012");
			} else if (LoginType.IOS.getFlag().equals(loginType)) {
				entity.setMnpltType("OLOG0014");
			} else {
				entity.setMnpltType("OLOG0014");
			}
			entity.setSystemId("CLOUD_CAN_V2.0");
			loginService.saveSysOperateLog(entity);
	    }else{
	        status.setComplete();
	    }
	    return "1";
	}
	
    /**
     * @param request
     * @param response
     * @return
     * @throws Exception
     * @author:Fisher
     * @email:zhuangcaijin@126.com
     * @创建日期:2015-3-4
     * @功能说明：session失效
     */
    @RequestMapping("/commonSessionExpired")
    public ModelAndView commonSessionExpired(HttpServletRequest request, HttpServletResponse response) throws Exception {
        return new ModelAndView("common/expired");
    }
    
    
   /**
    * 
    * @param entity
    * @param response
    * @param request
    * @throws Exception
    * @author:Lan
    * @email:763836737@qq.com
    * @创建日期:2015-3-30
    * @功能说明：修改密码
    */
    @RequestMapping("/getModifyPassWordForMobile")
    @ResponseBody
    public Object getModifyPassWordForMobile() throws Exception{
        ReturnResult returnResult = null;
        try {
            JSONObject JSONParams = this.getParameter_JSON();
            //String acctName = AppUtil.isNotEmpty(JSONParams.get("acctName"), "用户名").toString();
            String oldPass = AppUtil.isNotEmpty(JSONParams.get("oldPass"), "密码").toString();
            String newPass = AppUtil.isNotEmpty(JSONParams.get("newPass"), "密码").toString();
            String confirmPass = AppUtil.isNotEmpty(JSONParams.get("confirmPass"), "密码").toString();
            //String corpId = AppUtil.isNotEmpty(JSONParams.get("corpId"), "企业id").toString();
            SysUserEntity currentUser = this.getPhoneCurrentUser();
            SysUserEntity entity = (SysUserEntity) sysUserService.findById(currentUser.getId(), SysUserEntity.class);
            //entity.setAcctName(acctName);
            //entity.setCorpId(corpId);
            ReturnResult result = this.getReturnResult();
            //验证旧密码
            entity.setPassword(oldPass);
            int count = sysUserService.findPassByName(entity);
            entity.setNewPass(newPass);
            if(count>0 && PubUtil.isNotEmpty(entity.getNewPass()) && entity.getNewPass().equals(confirmPass)){
                SysUserEntity userEntity = sysUserService.findSysUserByName(entity);
                entity.setPassword(confirmPass);
                entity.setId(userEntity.getId());
                entity.setCode(userEntity.getCode());
                entity.setCorpId(userEntity.getCorpId());
                entity.setUserType(userEntity.getUserType());
                entity.setName(userEntity.getName());
                entity.setCorpId(userEntity.getCorpId());
                sysUserService.commonUpdatePass(entity);
                result.setMsg("操作成功");
                result.setSuccess(true);
                result.setMsgType("1");
                return new ReturnResult("操作成功", "1", true);
            }else{
            	result.setMsg("操作失败");
                result.setSuccess(false);
                result.setMsgType("0");
                return new ReturnResult("操作失败", "0", false);
            }
        } catch(ParameterFormatException e){
            returnResult = new ReturnResult(e.getMessage(), "0", false);
        } catch(ParameterIsNullException e){
            returnResult =  new ReturnResult(e.getMessage(), "0", false);
        } catch(Exception e){
            returnResult =  new ReturnResult(e.getMessage(), "0", false);
        } 
        return returnResult;
    }
    
    /**
     * 
     * @param entity
     * @param response
     * @param request
     * @throws Exception
     * @author:Lan
     * @email:763836737@qq.com
     * @创建日期:2015-3-30
     * @功能说明：获取用户信息
     */
     @RequestMapping("/getSysUserByNameForMobile")
     private void getSysUserByNameForMobile(SysUserEntity entity,HttpServletResponse response,HttpServletRequest request) throws Exception {
         SysUserEntity user = (SysUserEntity)request.getSession().getAttribute("SES_CURRENTUSER");
         entity.setName(user.getName());
         reslutVo.setObj(sysUserService.findSysUserByName(entity));
         ResponseUtil.responseJSON(reslutVo, response);
     }
     
     //TODO
//     /**
//      * 
//      * @param entity
//      * @param response
//      * @param request
//      * @param map
//      * @throws Exception
//      * @author:Lan
//      * @email:763836737@qq.com
//      * @创建日期:2015-4-1
//      * @功能说明： 最新公告
//      */
//     @SuppressWarnings("unchecked")
//     @RequestMapping("/getNewAnnouncementForMobile")
//     private void getNewAnnouncementForMobile(SysUserEntity entity,HttpServletResponse response,HttpServletRequest request, Map<String, Object> map) throws Exception {
//         Calendar cal = Calendar.getInstance();
//         List<String> orgIdList = (List<String>)map.get("SES_ORGANLIST");
//         SaveEnergyDrvVo maxSaveEnergyDrvVo = new SaveEnergyDrvVo();
//         SaveEnergyDrvVo minSaveEnergyDrvVo = new SaveEnergyDrvVo();
//         SafeBehaviourVo minSafeBehaviourVo = new SafeBehaviourVo();
//         SearchConditionVo vo = new SearchConditionVo();
//             
//         if(PubUtil.isNotEmpty(orgIdList)){
//             //获取昨天时间
//             cal.setTime(new Date());
//             cal.add(Calendar.DATE,-1);
//             String curTimeStr = DateTool.SHORT_DATE_FORMAT.format(cal.getTime());
//             //获取昨日最安全驾驶员
//             EnergySavingParamVo params = new EnergySavingParamVo();
//             SysUserEntity user = (SysUserEntity)request.getSession().getAttribute("SES_CURRENTUSER");
//             params.setCorpId(user.getCorpId());
//             params.setDriverRelTableName("T_COMM_DRV_SCT_BHV_INFO");
//             params.setBeginTime(curTimeStr + " 00:00:00");
//             params.setEndTime(curTimeStr + " 23:59:59");
//             List<String> lineList = baseLineInfoService.getBaseLineInfoListByOrganIds(orgIdList);
//             params.setOrgIds(lineList);
//             //添加到临时表数据
//             safeBehaviourService.saveAppDrvSctBhvChkInfo(safeBehaviourService.getSafeBehaviourData(params));
//             Pagination safeBehaviourPage = safeBehaviourService.getSafeBehaviour(params,request);
//             
//             if(PubUtil.isNotEmpty(safeBehaviourPage.getData())){
//                 minSafeBehaviourVo = (SafeBehaviourVo)safeBehaviourPage.getData().get(0);
//             }
//             
//             //获取昨日最节能驾驶员
//             vo.setBeginTime(curTimeStr + " 00:00:00");
//             vo.setEndTime(curTimeStr);
//             vo.setOrgIds(orgIdList);
//             List<SaveEnergyDrvVo> saveEnergyList = indexService.getDrvSaveEnergyList(vo);
//             if(PubUtil.isNotEmpty(saveEnergyList)){
//                 maxSaveEnergyDrvVo = saveEnergyList.get(0);
//                 minSaveEnergyDrvVo = saveEnergyList.get(saveEnergyList.size()-1);
//             }
//             
//             //上月故障最高
//             cal.setTime(new Date());
//             cal.add(Calendar.MONTH,-1);
//             vo = DateTool.getMonthDuring(vo, cal.getTime());
//             vo.setOrgIds(orgIdList);
//             List<MaxFaultDrvVo> list = indexService.getMaxFaultDrv(vo);
//             if(PubUtil.isNotEmpty(list)){
//                 map.put("minFaultDrv", list.get(0));
//             }
//         }
//         map.put("minFaultDrv", new MaxFaultDrvVo());
//         map.put("minSafeBehaviour", minSafeBehaviourVo);
//         map.put("minSaveEnergyDrv", minSaveEnergyDrvVo);
//         map.put("maxSaveEnergyDrv", maxSaveEnergyDrvVo);
//         reslutVo.setData(map);
//         ResponseUtil.responseJSON(reslutVo, response);
//     }
     
     
     
     
}
